import { useStore } from '@/hooks';
import { Form, Input, ResponsiveGrid, Table } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import PriceCell from './PriceCell';

const { Cell } = ResponsiveGrid;

const SurchargesTable = (props) => {
  const {
    dataSource,
    taskFormData,
    handleChange,
    mode,
  } = props;
  const { orderChangeStore: store } = useStore();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const isFromMerchant = !!taskFormData?.ORDER?.merchant;

  useEffect(() => {
    setSelectedKeys(() => (dataSource?.defaultKey));
  }, [dataSource]);


  const rowSelectionProps = {
    onChange: (v) => handleSurchargePicked(v),
    selectedRowKeys: selectedKeys,
    getProps: (r) => ({
      disabled: mode === 'edit' ? r.disabled : true,
    }),
  };

  const summaryPrice = countSummary(toJS(rowSelectionProps?.selectedRowKeys));

  function handleSurchargePicked(allSelectKeysTmp = []) {
    const { selectedMerchantSurKeys: excludeKeys } = taskFormData;
    const allSelectKeys = [...allSelectKeysTmp].filter((key) => (!excludeKeys.includes(key)));
    setSelectedKeys(allSelectKeys);
    handleChange(taskFormData, { name: 'selectedSurKeys', value: allSelectKeys });
  }

  function countSummary(selectKeys) {
    const surcharge = dataSource?.tableData || [];
    const res = selectKeys?.reduce((result, key) => {
      const { RMB = 0 } = surcharge?.find((e) => e.name === key)?.price || {};
      result += Number(RMB);
      return result;
    }, 0);
    return res || 0;
  }

  const tableColumns = [
    {
      title: t`附加服务`,
      dataIndex: 'name',
    },
    {
      title: t`${isFromMerchant ? '渠道附加费' : '平台附加费'}价格`,
      dataIndex: 'price',
      cell: (v, r) => {
        return (
          <PriceCell value={v} key={`priceCell- ${r?.name}`} />
        );
      },
    },
  ];

  return (
    <>
      <Table
        style={{ textAlign: 'center' }}
        primaryKey="name"
        dataSource={toJS(dataSource?.tableData)}
        columns={tableColumns}
        rowSelection={toJS(rowSelectionProps)}
      />
      <ResponsiveGrid gap={[0, 24]} columns={4}>
        <Cell colSpan={4}>
          <Form.Item
            isPreview
            label={t`附加费用`}
            style={{ width: '100%', display: 'flex', margin: 0 }}
          >
            <Input
              value={summaryPrice}
            />
          </Form.Item>
        </Cell>
      </ResponsiveGrid>
    </>
  );
};

export default observer(SurchargesTable);
